package com.ruoyi.business.namage;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import com.ruoyi.business.domain.DocDirectory;
import com.ruoyi.business.domain.FileInternetExport;
import com.ruoyi.business.domain.FileIntranetExport;
import com.ruoyi.business.domain.FilePerson;
import com.ruoyi.business.domain.bo.FileAttachmentBo;
import com.ruoyi.business.domain.bo.PersonFileBo;
import com.ruoyi.business.domain.vo.DocDirectoryVo;
import com.ruoyi.business.domain.vo.FileAttachmentVo;
import com.ruoyi.business.domain.vo.PersonFileVo;
import com.ruoyi.business.dto.FileMultipartFile;
import com.ruoyi.business.dto.PdfMultipartFile;
import com.ruoyi.business.service.IDocDirectoryService;
import com.ruoyi.business.service.IFileAttachmentService;
import com.ruoyi.business.service.IFilePersonService;
import com.ruoyi.business.service.IPersonFileService;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.service.OssService;
import com.ruoyi.system.service.ISysUserService;
import jakarta.servlet.http.HttpServletResponse;
import jodd.io.ZipUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import java.util.List;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

@Component
public class FileExportManager {
    @Autowired
    private IDocDirectoryService docDirectoryService;
    @Autowired
    private IPersonFileService personFileService;
    @Autowired
    private IFileAttachmentService fileAttachmentService;
    @Autowired
    private IFilePersonService filePersonService;
    @Autowired
    private OssService ossService;
    @Autowired
    private ISysUserService sysUserService;


    public void internetExport(HttpServletResponse response, FileInternetExport fileInternetExport) {
        if ("0".equals(fileInternetExport.getExportFormat())) {
            exportFolder(response, fileInternetExport);
        } else {
            exportPDF(response, fileInternetExport);
        }
    }

    public void intranetExport(FileIntranetExport fileIntranetExport) {
        if ("0".equals(fileIntranetExport.getExportFormat())) {
            exportFolder(fileIntranetExport);
        } else {
            exportPDF(fileIntranetExport);
        }
    }

    /**
     * 文件夹导出
     *
     * @param response
     * @param fileInternetExport
     */
    private void exportFolder(HttpServletResponse response, FileInternetExport fileInternetExport) {
        // 创建File对象
        Long personId = fileInternetExport.getExportedPerson();
        String fileType = fileInternetExport.getFileType();
        List<String> fileTypes = Collections.emptyList();
        if (StrUtil.isNotBlank(fileType)) {
            fileTypes = CollUtil.newArrayList(fileType.split(","));
        }
        Path tempDirectory = null;
        try {
            tempDirectory = Files.createTempDirectory(null);
        } catch (IOException e) {
        }

        Map<Long, List<FileAttachmentVo>> personFileMap = new HashMap<>();

        List<Tree<Long>> treeList = getExportFileTree(personId, fileTypes, personFileMap);

        try {
            FilePerson filePerson = filePersonService.selectFilePersonById(personId);
            Path mainPath = Paths.get(tempDirectory.toString(), filePerson.getName());
            createFileList(personFileMap, treeList, Files.createDirectories(mainPath));
            File zip = ZipUtil.zip(mainPath.toFile());
            //将文件写入响应流
            InputStream inputStream = Files.newInputStream(zip.toPath());
            int available = inputStream.available();
            IoUtil.copy(inputStream, response.getOutputStream(), available);
            response.setContentLength(available);

        } catch (Exception ignored) {
            throw new RuntimeException("文件下载异常");
        } finally {
            if (tempDirectory != null) {
                FileUtil.del(tempDirectory);
            }
        }

    }


    /**
     * 文件夹内网导出
     *
     * @param fileIntranetExport
     */
    private void exportFolder(FileIntranetExport fileIntranetExport) {
        // 创建File对象
        Long personId = fileIntranetExport.getExportedPerson();
        String fileType = fileIntranetExport.getFileType();
        Long applicant = fileIntranetExport.getApplicant();
        List<String> fileTypes = Collections.emptyList();
        if (StrUtil.isNotBlank(fileType)) {
            fileTypes = CollUtil.newArrayList(fileType.split(","));
        }
        Path tempDirectory = null;
        try {
            tempDirectory = Files.createTempDirectory(null);
        } catch (IOException e) {
        }

        Map<Long, List<FileAttachmentVo>> personFileMap = new HashMap<>();

        List<Tree<Long>> treeList = getExportFileTree(personId, fileTypes, personFileMap);

        try {
            FilePerson filePerson = filePersonService.selectFilePersonById(personId);
            Path mainPath = Paths.get(tempDirectory.toString(), filePerson.getName());
            createFileList(personFileMap, treeList, Files.createDirectories(mainPath));
            File zip = ZipUtil.zip(mainPath.toFile());

            FileMultipartFile fileMultipartFile = new FileMultipartFile(zip, "application/zip");

            SysUser applyUser = sysUserService.selectUserById(applicant);

            R ajaxResult = com.ruoyi.common.utils.FileUtil.doPostFileStreamAndJsonObj(fileMultipartFile, applyUser);
            if (R.isError(ajaxResult)) {
                throw new RuntimeException("文件推送异常:" + ajaxResult.getMsg());
            }
        } catch (Exception ignored) {
            throw new RuntimeException("文件推送异常");
        } finally {
            if (tempDirectory != null) {
                FileUtil.del(tempDirectory);
            }
        }
    }


    /**
     * 合并PDF导出
     *
     * @param response
     * @param fileInternetExport
     */
    private void exportPDF(HttpServletResponse response, FileInternetExport fileInternetExport) {
        FontFactory.register("/fonts/simsun.ttc", "simsun");

        Long personId = fileInternetExport.getExportedPerson();
        String fileType = fileInternetExport.getFileType();
        List<String> fileTypes = Collections.emptyList();
        if (StrUtil.isNotBlank(fileType)) {
            fileTypes = CollUtil.newArrayList(fileType.split(","));
        }
        FilePerson filePerson = filePersonService.selectFilePersonById(personId);
        String filename = filePerson.getName() + "档案导出.pdf";

        //用来存储每种类型的文件列表
        Map<Long, List<FileAttachmentVo>> personFileMap = new HashMap<>();

        //根据条件得到导出的目录树结构
        List<Tree<Long>> treeList = this.getExportFileTree(personId, fileTypes, personFileMap);

        ByteArrayOutputStream pdfOutputStream = this.createDocument(filePerson.getName() + "档案", treeList, personFileMap);


        // 直接使用内存中的PDF字节数组创建zip
        try (ByteArrayOutputStream zipOutputStream = new ByteArrayOutputStream();
             ZipOutputStream zip = new ZipOutputStream(zipOutputStream)) {

            zip.putNextEntry(new ZipEntry(filename));
            zip.write(pdfOutputStream.toByteArray()); // 直接写入内存数据
            zip.closeEntry();

            // 输出到response
            response.setContentLength(zipOutputStream.size());
            IoUtil.write(response.getOutputStream(), false, zipOutputStream.toByteArray());
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    /**
     * 内网合并PDF导出
     *
     * @param fileIntranetExport
     */
    private void exportPDF(FileIntranetExport fileIntranetExport) {
        FontFactory.register("/fonts/simsun.ttc", "simsun");

        Long personId = fileIntranetExport.getExportedPerson();
        String fileType = fileIntranetExport.getFileType();
        Long applicant = fileIntranetExport.getApplicant();

        List<String> fileTypes = Collections.emptyList();
        if (StrUtil.isNotBlank(fileType)) {
            fileTypes = CollUtil.newArrayList(fileType.split(","));
        }
        FilePerson filePerson = filePersonService.selectFilePersonById(personId);
        String filename = filePerson.getName() + "档案导出.pdf";

        //用来存储每种类型的文件列表
        Map<Long, List<FileAttachmentVo>> personFileMap = new HashMap<>();

        //根据条件得到导出的目录树结构
        List<Tree<Long>> treeList = this.getExportFileTree(personId, fileTypes, personFileMap);

        ByteArrayOutputStream pdfOutputStream = this.createDocument(filePerson.getName() + "档案", treeList, personFileMap);

        SysUser applyUser = sysUserService.selectUserById(applicant);

        try {
            PdfMultipartFile pdfMultipartFile = new PdfMultipartFile(pdfOutputStream, filename);
            R<String> ajaxResult = com.ruoyi.common.utils.FileUtil.doPostFileStreamAndJsonObj(pdfMultipartFile, applyUser);
            if (R.isError(ajaxResult)) {
                throw new RuntimeException("文件推送异常:" + ajaxResult.getMsg());
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }


    }

    private List<Path> createFileList(Map<Long, List<FileAttachmentVo>> personFileMap, List<Tree<Long>> treeList, Path path) throws IOException, BadElementException {
        List<Path> files = new ArrayList<>();
        for (Tree<Long> tree : treeList) {
            Path tempPath = Paths.get(path.toString(), (String) tree.getName());
            tempPath = Files.createDirectories(tempPath);
            if (tree.hasChild()) {
                createFileList(personFileMap, tree.getChildren(), tempPath);
            } else {
                List<FileAttachmentVo> personFileList = personFileMap.get(tree.getId());
                if (CollUtil.isNotEmpty(personFileList)) {
                    for (FileAttachmentVo fileAttachmentVo : personFileList) {
                        String ossUrl = ossService.selectUrlByIds(String.valueOf(fileAttachmentVo.getArchivalId()));
                        URL url = new URL(ossUrl);
                        OutputStream fos;
                        try (InputStream is = url.openStream()) {
                            fos = Files.newOutputStream(Files.createTempFile(tempPath, fileAttachmentVo.getName(), ".jpg"));
                            byte[] buffer = new byte[1024];
                            int length;

                            while ((length = is.read(buffer)) != -1) {
                                fos.write(buffer, 0, length);
                            }
                            is.close();
                        }
                        fos.close();
                    }
                }
            }
            files.add(tempPath);
        }
        return files;
    }


    /**
     * 查询人员导出的目录结构
     *
     * @param personId      人员id
     * @param fileTypes     文件类型
     * @param personFileMap 用来存储人员文件信息
     * @return
     */
    private List<Tree<Long>> getExportFileTree(Long personId, List<String> fileTypes, Map<Long, List<FileAttachmentVo>> personFileMap) {
        List<DocDirectoryVo> list = docDirectoryService.selectDocDirectoryList(new DocDirectory());
        //过滤出要求导出的类型
        List<DocDirectoryVo> exportDiredotyList = list.stream()
                .filter(i -> fileTypes.contains(String.valueOf(i.getId())))
                .collect(Collectors.toList());

        List<PersonFileVo> personFileVos = personFileService.queryList(PersonFileBo.builder().personId(personId).build());

        List<PersonFileVo> exportFileList = personFileVos.stream()
                .filter(i -> fileTypes.contains(String.valueOf(i.getId())))
                .collect(Collectors.toList());
        for (PersonFileVo personFile : exportFileList) {
            List<FileAttachmentVo> fileAttachmentVos = fileAttachmentService.queryList(FileAttachmentBo.builder().personFileId(personFile.getId()).build());
            personFileMap.put(personFile.getId(), fileAttachmentVos);
            DocDirectoryVo docDirectory = new DocDirectoryVo();
            docDirectory.setId(personFile.getId());
            docDirectory.setParentId(personFile.getFileType());
            docDirectory.setName(personFile.getName());
            docDirectory.setStatus("1");
            docDirectory.setFileFromTime(personFile.getFileFromTime());
            exportDiredotyList.add(docDirectory);
        }
        Set<DocDirectoryVo> exportDiredotySet = new HashSet<>(exportDiredotyList);
        Set<Long> missParentId;
        do {
            Set<Long> parenIdtSet = exportDiredotySet.stream().map(DocDirectoryVo::getParentId).collect(Collectors.toSet());
            Set<Long> idSet = exportDiredotySet.stream().map(DocDirectoryVo::getId).collect(Collectors.toSet());
            missParentId = parenIdtSet.stream().filter(i -> !idSet.contains(i) && i != 0L).collect(Collectors.toSet());
            Set<Long> finalMissParent = missParentId;
            Set<DocDirectoryVo> missParent = list.stream().filter(i -> finalMissParent.contains(i.getId())).collect(Collectors.toSet());
            exportDiredotySet.addAll(missParent);
        } while (!missParentId.isEmpty());
        List<Tree<Long>> treeList = TreeUtil.build(CollUtil.newArrayList(exportDiredotySet),
                0L, (entity, tree) -> {
                    tree.setId(entity.getId())
                            .setParentId(entity.getParentId())
                            .setName(entity.getName())
                            .setWeight(entity.getId())
                            .putExtra("coverImg", entity.getCoverImg());
                    tree.putExtra("fileFromTime", entity.getFileFromTime());
                    tree.putExtra("status", entity.getStatus());
                }

        );

        return treeList;
    }


    private ByteArrayOutputStream createDocument(String title, List<Tree<Long>> treeList, Map<Long, List<FileAttachmentVo>> personFileMap) {
        ByteArrayOutputStream pdfOutputStream = new ByteArrayOutputStream();
        PdfPTable table = this.genCatalogueTable(treeList, personFileMap);

        // 1. 创建文档对象
        Document document = new Document(PageSize.A4);
        try {
            PdfWriter.getInstance(document, pdfOutputStream);
            document.open();
            document.addTitle(title);
            document.add(table);
            this.fillDocument(document, treeList, personFileMap);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            document.close(); // 必须关闭文档
        }
        return pdfOutputStream;
    }


    private void fillDocument(Document document, List<Tree<Long>> treeList, Map<Long, List<FileAttachmentVo>> personFileMap) {
        if (CollUtil.isNotEmpty(treeList)) {
            for (Tree<Long> tree : treeList) {
                document.newPage();
                if (ObjUtil.equal(0L, tree.getParentId())) {
                    String coverImg = (String) tree.get("coverImg");
                    boolean insertCoverImg = false;
                    if (StrUtil.isNotBlank(coverImg)) {
                        String coverImgUrl = ossService.selectUrlByIds(coverImg);
                        try {
                            Image image = Image.getInstance(coverImgUrl);
                            float widthScale = PageSize.A4.getWidth() / image.getWidth();
                            float heightScale = PageSize.A4.getHeight() / image.getHeight();
                            float scale = Math.min(widthScale, heightScale);
                            image.scalePercent(scale * 100);
                            document.add(image);
                            insertCoverImg = true;
                        } catch (Exception e) {

                        }
                    }
                    if (!insertCoverImg) {
                        Font fontChinese = FontFactory.getFont("simsun", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
                        fontChinese.setSize(20);  // 设置字号
                        fontChinese.setStyle(Font.BOLD);  // 可选：加粗
                        // 创建带样式的段落
                        Paragraph centeredParagraph = new Paragraph(String.valueOf(tree.getName()), fontChinese);
                        centeredParagraph.setAlignment(Element.ALIGN_CENTER);  // 关键对齐设置
                        // 添加到文档（需确保document已打开）
                        try {
                            document.add(centeredParagraph);
                        } catch (DocumentException e) {
                        }
                    }
                } else if (ObjUtil.equals("1", tree.get("status"))) {
                    if (personFileMap.containsKey(tree.getId())) {
                        List<FileAttachmentVo> fileAttachmentVos = personFileMap.get(tree.getId());
                        for (FileAttachmentVo fileAttachmentVo : fileAttachmentVos) {
                            if (fileAttachmentVo.getArchivalImagery() != null) {
                                try {
                                    document.newPage();
                                    Image image = Image.getInstance(fileAttachmentVo.getArchivalImagery());
                                    float widthScale = PageSize.A4.getWidth() / image.getWidth();
                                    float heightScale = PageSize.A4.getHeight() / image.getHeight();
                                    float scale = Math.min(widthScale, heightScale);
                                    image.scalePercent(scale * 100);
                                    document.add(image);
                                } catch (DocumentException e) {
                                } catch (MalformedURLException e) {
                                    throw new RuntimeException(e);
                                } catch (IOException e) {
                                    throw new RuntimeException(e);
                                }
                            }
                        }
                    }
                } else {
                    Font fontChinese = FontFactory.getFont("simsun", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
                    fontChinese.setSize(16);  // 设置字号
                    fontChinese.setStyle(Font.BOLD);  // 可选：加粗
                    // 创建带样式的段落
                    Paragraph centeredParagraph = new Paragraph(String.valueOf(tree.getName()), fontChinese);
                    centeredParagraph.setAlignment(Element.ALIGN_CENTER);  // 关键对齐设置
                    // 添加到文档（需确保document已打开）
                    try {
                        document.add(centeredParagraph);
                    } catch (DocumentException e) {
                    }
                }

                fillDocument(document, tree.getChildren(), personFileMap);
            }
        }
    }

    /**
     * 生成目录表格
     *
     * @param treeList
     * @param personFileMap
     * @return
     */
    private PdfPTable genCatalogueTable(List<Tree<Long>> treeList, Map<Long, List<FileAttachmentVo>> personFileMap) {
        //计算每一个节点的页数，并返回总页数
        int count = this.fillPageCount(treeList, personFileMap);
        PdfPTable table = createPDFTable();//创建表格
        this.createPDFTableTitle(table, count);
        this.fillCatalogueTable(table, treeList);
        return table;
    }

    private int fillPageCount(List<Tree<Long>> treeList, Map<Long, List<FileAttachmentVo>> personFileMap) {
        int countPage = 0;
        if (CollUtil.isNotEmpty(treeList)) {
            for (Tree<Long> tree : treeList) {
                int count = 0;
                if (tree.hasChild()) {
                    count = this.fillPageCount(tree.getChildren(), personFileMap);
                } else if (personFileMap.containsKey(tree.getId())) {
                    count = personFileMap.get(tree.getId()).size();
                }
                tree.putExtra("pageCount", count);
                countPage += count;
            }
        }
        return countPage;
    }


    /**
     * 创建材料标题表头
     *
     * @param table
     * @param name
     * @return
     */

    private PdfPTable fillLevelOneDirectory(PdfPTable table, String index, String name) {
        Font fontChinese = FontFactory.getFont("simsun", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
        fontChinese.setStyle(Font.BOLD);

        // 构建每个单元格
        PdfPCell cell1 = new PdfPCell(new Paragraph(index, fontChinese));
        // 边框颜色
        cell1.setBorderColor(BaseColor.BLACK);
        // 设置背景颜色
        //cell1.setBackgroundColor(BaseColor.ORANGE);
        // 设置跨两行
        //cell1.setRowspan(2);
        // 设置距左边的距离
        cell1.setPaddingLeft(10);
        // 设置高度
        cell1.setFixedHeight(40);
        // 设置内容水平居中显示
        cell1.setHorizontalAlignment(Element.ALIGN_CENTER);
        // 设置垂直居中
        cell1.setVerticalAlignment(Element.ALIGN_MIDDLE);
        table.addCell(cell1);

        // 构建每个单元格
        PdfPCell cell2 = new PdfPCell(new Paragraph(name, fontChinese));
        // 边框颜色
        cell2.setBorderColor(BaseColor.BLACK);
        // 设置背景颜色
        //cell1.setBackgroundColor(BaseColor.ORANGE);
        //设置跨七列
        cell2.setColspan(6);
        // 设置跨两行
        //cell1.setRowspan(2);
        // 设置距左边的距离
        cell2.setPaddingLeft(10);
        // 设置高度
        cell2.setFixedHeight(40);
        // 设置内容水平居中显示
        cell2.setHorizontalAlignment(Element.ALIGN_LEFT);
        // 设置垂直居中
        cell2.setVerticalAlignment(Element.ALIGN_MIDDLE);
        table.addCell(cell2);

        return table;
    }

    /**
     * 创建材料二级标题表头
     *
     * @param table
     * @param name
     * @return
     */
    private PdfPTable fillLevelTwoDirectory(PdfPTable table, String name) {

        Font fontChinese = FontFactory.getFont("simsun", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);

        // 构建每个单元格
        PdfPCell cell1 = new PdfPCell(new Paragraph("", fontChinese));
        // 边框颜色
        cell1.setBorderColor(BaseColor.BLACK);
        // 设置距左边的距离
        cell1.setPaddingLeft(10);
        // 设置高度
        cell1.setFixedHeight(40);
        // 设置内容水平居中显示
        cell1.setHorizontalAlignment(Element.ALIGN_CENTER);
        // 设置垂直居中
        cell1.setVerticalAlignment(Element.ALIGN_MIDDLE);
        table.addCell(cell1);

        // 构建每个单元格
        PdfPCell cell2 = new PdfPCell(new Paragraph(name, fontChinese));
        // 边框颜色
        cell2.setBorderColor(BaseColor.BLACK);
        // 设置距左边的距离
        cell2.setPaddingLeft(10);
        // 设置高度
        cell2.setFixedHeight(40);
        // 设置内容水平居中显示
        cell2.setHorizontalAlignment(Element.ALIGN_LEFT);
        // 设置垂直居中
        cell2.setVerticalAlignment(Element.ALIGN_MIDDLE);
        table.addCell(cell2);

        // 构建每个单元格
        PdfPCell cell_year = new PdfPCell(new Paragraph("", fontChinese));
        // 边框颜色
        cell_year.setBorderColor(BaseColor.BLACK);
        // 设置距左边的距离
        cell_year.setPaddingLeft(10);
        // 设置高度
        cell_year.setFixedHeight(40);
        // 设置内容水平居中显示
        cell_year.setHorizontalAlignment(Element.ALIGN_CENTER);
        // 设置垂直居中
        cell_year.setVerticalAlignment(Element.ALIGN_MIDDLE);
        table.addCell(cell_year);

        // 构建每个单元格
        PdfPCell cell_month = new PdfPCell(new Paragraph("", fontChinese));
        // 边框颜色
        cell_month.setBorderColor(BaseColor.BLACK);
        // 设置距左边的距离
        cell_month.setPaddingLeft(10);
        // 设置高度
        cell_month.setFixedHeight(40);
        // 设置内容水平居中显示
        cell_month.setHorizontalAlignment(Element.ALIGN_CENTER);
        // 设置垂直居中
        cell_month.setVerticalAlignment(Element.ALIGN_MIDDLE);
        table.addCell(cell_month);

        // 构建每个单元格
        PdfPCell cell_Day = new PdfPCell(new Paragraph("", fontChinese));
        // 边框颜色
        cell_Day.setBorderColor(BaseColor.BLACK);
        // 设置距左边的距离
        cell_Day.setPaddingLeft(10);
        // 设置高度
        cell_Day.setFixedHeight(40);
        // 设置内容水平居中显示
        cell_Day.setHorizontalAlignment(Element.ALIGN_CENTER);
        // 设置垂直居中
        cell_Day.setVerticalAlignment(Element.ALIGN_MIDDLE);
        table.addCell(cell_Day);

        // 构建每个单元格
        PdfPCell cell_Page = new PdfPCell(new Paragraph("", fontChinese));
        // 边框颜色
        cell_Page.setBorderColor(BaseColor.BLACK);
        // 设置距左边的距离
        cell_Page.setPaddingLeft(10);
        // 设置高度
        cell_Page.setFixedHeight(40);
        // 设置内容水平居中显示
        cell_Page.setHorizontalAlignment(Element.ALIGN_CENTER);
        // 设置垂直居中
        cell_Page.setVerticalAlignment(Element.ALIGN_MIDDLE);
        table.addCell(cell_Page);

        // 构建每个单元格
        PdfPCell cell_remark = new PdfPCell(new Paragraph("", fontChinese));
        // 边框颜色
        cell_remark.setBorderColor(BaseColor.BLACK);
        // 设置距左边的距离
        cell_remark.setPaddingLeft(10);
        // 设置高度
        cell_remark.setFixedHeight(40);
        // 设置内容水平居中显示
        cell_remark.setHorizontalAlignment(Element.ALIGN_CENTER);
        // 设置垂直居中
        cell_remark.setVerticalAlignment(Element.ALIGN_MIDDLE);
        table.addCell(cell_remark);

        return table;
    }


    /**
     * 填充表格目录
     *
     * @param treeList
     * @return
     */
    private void fillCatalogueTable(PdfPTable catalogueTable, List<Tree<Long>> treeList) {
        List<String> levelOneIndex = CollUtil.newArrayList("一", "二", "三", "四", "五", "六", "七", "八", "九", "十");
        List<String> levelTowIndex = CollUtil.newArrayList("1、", "2、", "3、", "4、", "5、", "6、", "7、", "8、", "9、", "10、");
        int index = 0;

        for (Tree<Long> tree : treeList) {
            if (tree.getParentId() == 0L) {
                this.fillLevelOneDirectory(catalogueTable, levelOneIndex.get(index), (String) tree.getName());
            } else if (ObjUtil.equal(tree.get("status"), "1")) {
                this.fillPersonFileContent(catalogueTable, (String) tree.getName(), (Date) tree.get("fileFromTime"), (Integer) tree.get("pageCount"));
            } else {
                this.fillLevelTwoDirectory(catalogueTable, levelTowIndex.get(index) + tree.getName());
            }

            if (tree.hasChild()) {
                fillCatalogueTable(catalogueTable, tree.getChildren());
            }
            index++;
        }
    }


    /**
     * 创建表格
     *
     * @return
     * @throws DocumentException
     */
    private PdfPTable createPDFTable() {
        // 添加表格，7列
        PdfPTable table = new PdfPTable(7);
        //设置表格宽度比例为%100
        table.setWidthPercentage(100);
        // 设置表格的宽度
        table.setTotalWidth(500);
        try {
            // 也可以每列分别设置宽度
            table.setTotalWidth(new float[]{60, 200, 60, 60, 60, 60, 60});
        } catch (DocumentException e) {
            throw new RuntimeException("表格创建失败");
        }
        // 锁住宽度
        table.setLockedWidth(true);
        // 设置表格上面空白宽度
        table.setSpacingBefore(10f);
        // 设置表格下面空白宽度
        table.setSpacingAfter(10f);
        // 设置表格默认为无边框
        table.getDefaultCell().setBorder(0);

        return table;
    }


    /**
     * 创建表格标题
     *
     * @param table
     * @return
     */
    private void createPDFTableTitle(PdfPTable table, int countPage) {
        Font fontChinese = FontFactory.getFont("simsun", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
        // 构建每个单元格
        PdfPCell cell1 = new PdfPCell(new Paragraph("干部人事档案目录", fontChinese));
        // 边框颜色
        cell1.setBorderColor(BaseColor.BLACK);
        // 设置背景颜色
        //cell1.setBackgroundColor(BaseColor.ORANGE);
        //设置跨七列
        cell1.setColspan(7);
        // 设置跨两行
        //cell1.setRowspan(2);
        // 设置距左边的距离
        cell1.setPaddingLeft(10);
        // 设置高度
        cell1.setFixedHeight(40);
        // 设置内容水平居中显示
        cell1.setHorizontalAlignment(Element.ALIGN_CENTER);
        // 设置垂直居中
        cell1.setVerticalAlignment(Element.ALIGN_MIDDLE);
        table.addCell(cell1);

        // 构建每个单元格
        PdfPCell cell_code = new PdfPCell(new Paragraph("XXX", fontChinese));
        // 边框颜色
        cell_code.setBorderColor(BaseColor.BLACK);
        // 设置背景颜色
        //设置跨七列
        cell_code.setColspan(7);
        // 设置内容水平居中显示
        cell_code.setHorizontalAlignment(Element.ALIGN_RIGHT);
        // 设置垂直居中
        cell_code.setVerticalAlignment(Element.ALIGN_MIDDLE);
        table.addCell(cell_code);

        // 构建每个单元格
        PdfPCell cell_no = new PdfPCell(new Paragraph("序号", fontChinese));
        // 边框颜色
        cell_no.setBorderColor(BaseColor.BLACK);

        //设置跨两行
        cell_no.setRowspan(2);
        // 设置内容水平居中显示
        cell_no.setHorizontalAlignment(Element.ALIGN_CENTER);
        // 设置垂直居中
        cell_no.setVerticalAlignment(Element.ALIGN_MIDDLE);
        table.addCell(cell_no);

        // 构建每个单元格
        PdfPCell cell_name = new PdfPCell(new Paragraph("材料名称", fontChinese));
        // 边框颜色
        cell_name.setBorderColor(BaseColor.BLACK);

        //设置跨两行
        cell_name.setRowspan(2);
        // 设置内容水平居中显示
        cell_name.setHorizontalAlignment(Element.ALIGN_CENTER);
        // 设置垂直居中
        cell_name.setVerticalAlignment(Element.ALIGN_MIDDLE);
        table.addCell(cell_name);

        // 构建每个单元格
        PdfPCell cell_time = new PdfPCell(new Paragraph("材料形成时间", fontChinese));
        // 边框颜色
        cell_time.setBorderColor(BaseColor.BLACK);

        //设置跨两行
        cell_time.setColspan(3);
        // 设置内容水平居中显示
        cell_time.setHorizontalAlignment(Element.ALIGN_CENTER);
        // 设置垂直居中
        cell_time.setVerticalAlignment(Element.ALIGN_MIDDLE);
        table.addCell(cell_time);

        // 构建每个单元格
        PdfPCell cell_page = new PdfPCell(new Paragraph("页数", fontChinese));
        // 边框颜色
        cell_page.setBorderColor(BaseColor.BLACK);

        // 设置内容水平居中显示
        cell_page.setHorizontalAlignment(Element.ALIGN_CENTER);
        // 设置垂直居中
        cell_page.setVerticalAlignment(Element.ALIGN_MIDDLE);
        table.addCell(cell_page);


        // 构建每个单元格
        PdfPCell cell_remark = new PdfPCell(new Paragraph("备注", fontChinese));
        // 边框颜色
        cell_remark.setBorderColor(BaseColor.BLACK);

        // 设置内容水平居中显示
        cell_remark.setHorizontalAlignment(Element.ALIGN_CENTER);
        // 设置垂直居中
        cell_remark.setVerticalAlignment(Element.ALIGN_MIDDLE);
        table.addCell(cell_remark);


        // 构建每个单元格
        PdfPCell cell_year = new PdfPCell(new Paragraph("年", fontChinese));
        // 边框颜色
        cell_year.setBorderColor(BaseColor.BLACK);

        // 设置内容水平居中显示
        cell_year.setHorizontalAlignment(Element.ALIGN_CENTER);
        // 设置垂直居中
        cell_year.setVerticalAlignment(Element.ALIGN_MIDDLE);
        table.addCell(cell_year);


        // 构建每个单元格
        PdfPCell cell_month = new PdfPCell(new Paragraph("月", fontChinese));
        // 边框颜色
        cell_month.setBorderColor(BaseColor.BLACK);

        // 设置内容水平居中显示
        cell_month.setHorizontalAlignment(Element.ALIGN_CENTER);
        // 设置垂直居中
        cell_month.setVerticalAlignment(Element.ALIGN_MIDDLE);
        table.addCell(cell_month);

        // 构建每个单元格
        PdfPCell cell_day = new PdfPCell(new Paragraph("日", fontChinese));
        // 边框颜色
        cell_day.setBorderColor(BaseColor.BLACK);

        // 设置内容水平居中显示
        cell_day.setHorizontalAlignment(Element.ALIGN_CENTER);
        // 设置垂直居中
        cell_day.setVerticalAlignment(Element.ALIGN_MIDDLE);
        table.addCell(cell_day);

        // 构建每个单元格
        PdfPCell cell_page2 = new PdfPCell(new Paragraph("" + countPage, fontChinese));
        // 边框颜色
        cell_page2.setBorderColor(BaseColor.BLACK);

        // 设置内容水平居中显示
        cell_page2.setHorizontalAlignment(Element.ALIGN_CENTER);
        // 设置垂直居中
        cell_page2.setVerticalAlignment(Element.ALIGN_MIDDLE);
        table.addCell(cell_page2);

        // 构建每个单元格
        PdfPCell cell_remark2 = new PdfPCell(new Paragraph("", fontChinese));
        // 边框颜色
        cell_remark2.setBorderColor(BaseColor.BLACK);

        // 设置内容水平居中显示
        cell_remark2.setHorizontalAlignment(Element.ALIGN_CENTER);
        // 设置垂直居中
        cell_remark2.setVerticalAlignment(Element.ALIGN_MIDDLE);
        table.addCell(cell_remark2);
    }


    private PdfPTable fillPersonFileContent(PdfPTable table, String name, Date fileFromTime, int pageNum) {
        fileFromTime = fileFromTime == null ? new Date() : fileFromTime;
        Font fontChinese = FontFactory.getFont("simsun", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);

        // 构建每个单元格
        PdfPCell cell1 = new PdfPCell(new Paragraph("", fontChinese));
        // 边框颜色
        cell1.setBorderColor(BaseColor.BLACK);
        // 设置距左边的距离
        cell1.setPaddingLeft(10);
        // 设置高度
        cell1.setFixedHeight(40);
        // 设置内容水平居中显示
        cell1.setHorizontalAlignment(Element.ALIGN_CENTER);
        // 设置垂直居中
        cell1.setVerticalAlignment(Element.ALIGN_MIDDLE);
        table.addCell(cell1);

        // 构建每个单元格
        PdfPCell cell2 = new PdfPCell(new Paragraph(name, fontChinese));
        // 边框颜色
        cell2.setBorderColor(BaseColor.BLACK);
        // 设置距左边的距离
        cell2.setPaddingLeft(10);
        // 设置高度
        cell2.setFixedHeight(40);
        // 设置内容水平居中显示
        cell2.setHorizontalAlignment(Element.ALIGN_LEFT);
        // 设置垂直居中
        cell2.setVerticalAlignment(Element.ALIGN_MIDDLE);
        table.addCell(cell2);

        // 构建每个单元格
        PdfPCell cell_year = new PdfPCell(new Paragraph("" + DateUtil.year(fileFromTime), fontChinese));
        // 边框颜色
        cell_year.setBorderColor(BaseColor.BLACK);
        // 设置距左边的距离
        cell_year.setPaddingLeft(10);
        // 设置高度
        cell_year.setFixedHeight(40);
        // 设置内容水平居中显示
        cell_year.setHorizontalAlignment(Element.ALIGN_CENTER);
        // 设置垂直居中
        cell_year.setVerticalAlignment(Element.ALIGN_MIDDLE);
        table.addCell(cell_year);

        // 构建每个单元格
        PdfPCell cell_month = new PdfPCell(new Paragraph("" + (DateUtil.month(fileFromTime) + 1), fontChinese));
        // 边框颜色
        cell_month.setBorderColor(BaseColor.BLACK);
        // 设置距左边的距离
        cell_month.setPaddingLeft(10);
        // 设置高度
        cell_month.setFixedHeight(40);
        // 设置内容水平居中显示
        cell_month.setHorizontalAlignment(Element.ALIGN_CENTER);
        // 设置垂直居中
        cell_month.setVerticalAlignment(Element.ALIGN_MIDDLE);
        table.addCell(cell_month);

        // 构建每个单元格
        PdfPCell cell_Day = new PdfPCell(new Paragraph("" + DateUtil.dayOfMonth(fileFromTime), fontChinese));
        // 边框颜色
        cell_Day.setBorderColor(BaseColor.BLACK);
        // 设置距左边的距离
        cell_Day.setPaddingLeft(10);
        // 设置高度
        cell_Day.setFixedHeight(40);
        // 设置内容水平居中显示
        cell_Day.setHorizontalAlignment(Element.ALIGN_CENTER);
        // 设置垂直居中
        cell_Day.setVerticalAlignment(Element.ALIGN_MIDDLE);
        table.addCell(cell_Day);

        // 构建每个单元格
        PdfPCell cell_Page = new PdfPCell(new Paragraph("" + pageNum, fontChinese));
        // 边框颜色
        cell_Page.setBorderColor(BaseColor.BLACK);
        // 设置距左边的距离
        cell_Page.setPaddingLeft(10);
        // 设置高度
        cell_Page.setFixedHeight(40);
        // 设置内容水平居中显示
        cell_Page.setHorizontalAlignment(Element.ALIGN_CENTER);
        // 设置垂直居中
        cell_Page.setVerticalAlignment(Element.ALIGN_MIDDLE);
        table.addCell(cell_Page);

        // 构建每个单元格
        PdfPCell cell_remark = new PdfPCell(new Paragraph("", fontChinese));
        // 边框颜色
        cell_remark.setBorderColor(BaseColor.BLACK);
        // 设置距左边的距离
        cell_remark.setPaddingLeft(10);
        // 设置高度
        cell_remark.setFixedHeight(40);
        // 设置内容水平居中显示
        cell_remark.setHorizontalAlignment(Element.ALIGN_CENTER);
        // 设置垂直居中
        cell_remark.setVerticalAlignment(Element.ALIGN_MIDDLE);
        table.addCell(cell_remark);

        return table;
    }

}
